import { getNormalPath } from '@utils/baseMethods';
import tagsViewPinia from '@pinia/modules/tagsView';
import router from '@/router';
import { ComponentInternalInstance, computed, getCurrentInstance, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { RouteLocationRaw, useRoute, useRouter } from 'vue-router';
import { TagView } from '@pinia/types/tagsView';
import { constantRoutes } from '@/router';
import ScrollPane from '@com/tagsView/scrollPane/ScrollPane.vue';

export default function importConfig() {
  const base = reactive<any>({
    visible: false,
    top: 0,
    left: 0,
    selectedTag: {},
    affixTags: [],
    scrollPaneRef: ScrollPane,
    route: useRoute(),
    router: useRouter(),
    visitedViews: computed(() => tagsViewPinia().visitedViews),
    routes: computed(() => constantRoutes),
  });

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  watch(base.route, () => {
    addTags();
    moveToCurrentTag();
  });

  watch(
    () => base.visible,
    (value) => {
      if (value) {
        document.body.addEventListener('click', closeMenu);
      } else {
        document.body.removeEventListener('click', closeMenu);
      }
    },
  );

  const isActive = (r: TagView): boolean => {
    return r.path === base.route.path;
  };

  const activeStyle = (tag: TagView) => {
    if (!isActive(tag)) return {};
    // return {
    //   "background-color": theme.value,
    //   "border-color": theme.value
    // };
  };

  //不可关闭的标签返回 true，否则返回 false
  const isAffix = (tag: TagView) => {
    return tag.path == '/home' ? true : false;
    // return tag.meta && tag.meta.affix;
  };

  //是否为第一个标签
  const isFirstView = () => {
    try {
      return base.selectedTag.fullPath === '/home' || base.selectedTag.fullPath === base.visitedViews[1].fullPath;
    } catch (err) {
      return false;
    }
  };

  //是否为最后一个标签
  const isLastView = () => {
    try {
      return base.selectedTag.fullPath === base.visitedViews[base.visitedViews.length - 1].fullPath;
    } catch (err) {
      return false;
    }
  };

  //筛选出不可关闭的标签
  const filterAffixTags = (routes, basePath = '') => {
    let tags: TagView[] = [];
    routes.forEach((route) => {
      // if (route.meta && route.meta.affix) {
      if (route.path == '/home') {
        // const tagPath = getNormalPath(basePath + "/" + route.path);
        tags.push({
          fullPath: '/home',
          path: '/home',
          name: route.name,
          meta: { ...route.meta },
        });
      }
      if (route.children) {
        const tempTags = filterAffixTags(route.children, route.path);
        if (tempTags.length >= 1) {
          tags = [...tags, ...tempTags];
        }
      }
    });
    return tags;
  };

  //初始化标签列表
  const initTags = () => {
    const res = filterAffixTags(base.routes);
    base.affixTags = res;
    for (const tag of res) {
      // Must have tag name
      if (tag.name) {
        tagsViewPinia().addVisitedView(tag);
      }
    }
  };

  //点击左侧菜单，将未添加过的标签添加入标签列表
  const addTags = () => {
    const { name } = base.route;
    if (base.route.query.title) {
      base.meta.title = base.query.title;
    }
    if (name) {
      tagsViewPinia().addView(base.route);
      if (base.route.meta.link) {
        // tagsViewPinia().addIframeView(base.route);
      }
    }
    return false;
  };

  //移动至当前标签
  const moveToCurrentTag = () => {
    nextTick(() => {
      for (const r of base.visitedViews) {
        if (r.path === base.route.path) {
          proxy?.$refs.scrollPane.moveToTarget(r);
          // base.scrollPaneRef.moveToTarget(r);

          // when query is different then update
          if (r.to.fullPath !== base.route.fullPath) {
            tagsViewPinia().updateVisitedView(base.route);
          }
        }
      }
    });
  };
  //刷新当前标签页面
  const refreshSelectedTag = (view: TagView) => {
    tagsViewPinia()
      .delCachedView(view)
      .then(() => {
        const { fullPath, query } = view;
        nextTick(() => {
          router.replace({
            path: 'redirect' + fullPath,
            query: query,
          });
          // router.go(0);
        });
      });
  };
  //关闭当前标签页面
  const closeSelectedTag = (view: TagView) => {
    tagsViewPinia()
      .delView(view)
      .then(({ visitedViews }: any) => {
        if (isActive(view)) {
          toLastView(visitedViews, view);
        }
      });
  };
  //关闭当前标签左侧所有页面
  const closeLeftTags = () => {
    tagsViewPinia()
      .delLeftTags(base.selectedTag)
      .then((visitedViews) => {
        if (!visitedViews.find((i) => i.fullPath === base.route.fullPath)) {
          toLastView(visitedViews);
        }
      });
  };
  //关闭当前标签右侧所有页面
  const closeRightTags = () => {
    tagsViewPinia()
      .delRightTags(base.selectedTag)
      .then((visitedViews) => {
        if (!visitedViews.find((i) => i.fullPath === base.route.fullPath)) {
          toLastView(visitedViews);
        }
      });
  };
  //关闭除当前标签外其他标签页面
  const closeOthersTags = () => {
    router.push(base.selectedTag as RouteLocationRaw).catch(() => {});
    tagsViewPinia()
      .delOthersViews(base.selectedTag)
      .then(() => {
        moveToCurrentTag();
      });
  };
  //关闭所有页面
  const closeAllTags = (view: TagView) => {
    tagsViewPinia()
      .delAllViews()
      .then(({ visitedViews }) => {
        if (base.affixTags.some((tag) => tag.path === base.route.path)) {
          return;
        }
        toLastView(visitedViews, view);
      });
  };
  //去标签列表中的最后一个标签页面
  const toLastView = (visitedViews: TagView[], view?: TagView) => {
    const latestView = visitedViews.slice(-1)[0];
    if (latestView) {
      router.push(latestView.fullPath as string);
    } else {
      // now the default is to redirect to the home page if there is no tags-view,
      // you can adjust it according to your needs.
      if (view?.name === 'home') {
        // to reload home page
        router.replace({ path: view?.fullPath });
      } else {
        router.push('/');
      }
    }
  };
  //鼠标右键打开选择列表
  const openMenu = (tag: TagView, e: MouseEvent) => {
    const menuMinWidth = 105;
    const offsetLeft = proxy?.$el.getBoundingClientRect().left; // container margin left
    const offsetWidth = proxy?.$el.offsetWidth; // container width
    const maxLeft = offsetWidth - menuMinWidth; // left boundary
    const l = e.clientX - offsetLeft + 15; // 15: margin right

    if (l > maxLeft) {
      base.left = maxLeft;
    } else {
      base.left = l;
    }

    base.top = e.clientY;
    base.visible = true;
    base.selectedTag = tag;
  };

  //关闭选择列表
  const closeMenu = () => {
    base.visible = false;
  };
  //滚动事件
  const handleScroll = () => {
    closeMenu();
  };

  onMounted(() => {
    initTags();
    addTags();
  });

  return {
    base,
    isActive,
    activeStyle,
    isAffix,
    isFirstView,
    isLastView,
    filterAffixTags,
    initTags,
    addTags,
    moveToCurrentTag,
    refreshSelectedTag,
    closeSelectedTag,
    closeRightTags,
    closeLeftTags,
    closeOthersTags,
    closeAllTags,
    toLastView,
    openMenu,
    closeMenu,
    handleScroll,
  };
}
